package com.adams.action.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.adams.access.db.bean.Menu;
import com.adams.access.db.bean.Right;
import com.adams.access.db.bean.Role;
import com.adams.access.db.bean.ViewEvent;
import com.adams.action.view.ViewAction;
import com.adams.common.BaseAction;
import com.adams.common.Constants;
import com.adams.core.exception.BusinessException;
import com.adams.custom.page.mgt.service.ViewParseService;
import com.adams.custom.page.mgt.service.ViewRoleEventService;
import com.adams.info.AdamsConstant;
import com.adams.log.service.OptLogService;
import com.adams.right.service.RightService;
import com.adams.role.service.RoleService;
import com.adams.sys.menu.service.MenuService;

/**
 * 
 * 
 * File Name : RoleAction.java
 * 
 * @Description : 角色管理类
 * @author 902990封文进
 */
public class RoleAction extends BaseAction {

    private ViewParseService viewParseService;

    private RoleService roleService;

    private RightService rightService;

    private MenuService menuService;

    private OptLogService optLogService;

    private int menuId;

    private String gridPanelId;

    private String viewEventId;

    private String formPanelId;

    private String viewItemId;

    private String searchPanelId;

    private ViewRoleEventService viewRoleEventService;

    /**
     * 
     * Description : 显示布局
     * 
     * @return String
     * @throws Exception
     * 
     */
    @SuppressWarnings("unchecked")
    public String listPanel() throws Exception {
        // Map map = viewParseService.getParseViewByMenuId(getUserId(), menuId);
        // write(JSONObject.fromObject(map).toString());
        write(viewParseService.getParseViewJSONByMenuId(getUserId(), menuId));
        return null;
    }

    /**
     * Description : 显示查询条字段信息
     * 
     * @return
     * @throws Exception
     * 
     */
    public String listSearchItem() throws Exception {
        // Map map = viewParseService.getParseSearchItems(getUserId(), menuId,
        // searchPanelId);
        // write(JSONObject.fromObject(map).toString());
        write(viewParseService.getParseSearchItemsJSON(getUserId(), menuId, searchPanelId));
        return null;
    }

    /**
     * 
     * Description : 显示元素
     * 
     * @return String
     * @throws Exception
     * 
     */
    public String listGridStructure() throws Exception {
        write(viewParseService.getParseGridsJSON(getUserId(), gridPanelId));
        return null;
    }

    /**
     * 
     * Description : 显示数据
     * 
     * @return String
     * @throws Exception
     * 
     */
    @SuppressWarnings("unchecked")
    public String listGridData() throws Exception {
        Map inputMap = ViewAction.requestParameterMap2Map(request);
        Map map = viewParseService.getParseGridDatas(getUserId(), gridPanelId, searchPanelId, inputMap);
        write(JSONObject.fromObject(map).toString());
        return null;
    }

    /**
     * 
     * Description : 查询权限
     * 
     * @return String
     * @throws Exception
     * 
     */
    @SuppressWarnings("unchecked")
    public String getRights() throws Exception {
        List<Menu> list = menuService.querySubMenus(Long.valueOf("0"));
        if (list != null && list.size() > 0) {
            List<Map> result = new ArrayList<Map>();
            List<Menu> subMenuList;
            for (Menu menu : list) {
                Map map = new HashMap();
                setMenuMap(map, menu);
                // map.put("text", menu.getMenuName());
                // map.put("id", menu.getId());
                // map.put("cls", "folder");
                // map.put("checked", isChecked(menu.getMenuCode()));
                //
                // // 子节点
                // subMenuList = menuService.querySubMenus(menu.getId());
                // if (subMenuList != null && subMenuList.size() > 0)
                // {
                // List<Map> children = new ArrayList<Map>();
                // for (Menu m : subMenuList)
                // {
                // Map subMap = new HashMap();
                // subMap.put("text", m.getMenuName());
                // subMap.put("id", m.getId());
                // subMap.put("leaf", true);
                // subMap.put("checked", isChecked(m.getMenuCode()));
                //
                // children.add(subMap);
                // }
                // map.put("leaf", false);
                // map.put("children", children);
                //
                // } else
                // {
                // map.put("leaf", true);
                // }

                result.add(map);

            }
            write(JSONArray.fromObject(result).toString());
        }
        return null;
    }

    private void setMenuMap(Map map, Menu menu) throws BusinessException {
        map.put("text", menu.getMenuName());
        map.put("id", menu.getId());
        map.put("cls", "folder");
        map.put("checked", isChecked(menu.getMenuCode()));
        map.put("expanded", true);
  
        String roleId = request.getParameter("roleId");
        // 子节点
        List<Menu> subMenuList = menuService.querySubMenus(menu.getId());
        if (subMenuList != null && subMenuList.size() > 0) {
            List<Map> children = new ArrayList<Map>();
            for (Menu m : subMenuList) {
                Map subMap = new HashMap();
                setMenuMap(subMap, m);
                children.add(subMap);
            }
            map.put("leaf", false);
            map.put("children", children);

        } else {

            // 如果是叶子节点，添加一级事件
            // 根据menuID查出event事件TEXT
            // sql =select event.* from t_menu menu ,t_view_win_info win
            // ,t_view_panel_info panel , t_view_event_info event where
            // menu.id=win.MENUID and win.id=panel.VIEWWINID and
            // panel.id=event.VIEWPANELID and menu.id=3
            List<ViewEvent> eventList = viewRoleEventService.getEventsByMeunId(menu.getId().intValue());
            List<Map> children = new ArrayList<Map>();
            if (eventList == null) {
                map.put("leaf", true);
            } else {
             
                for (ViewEvent event : eventList) {
                    Map subMap = new HashMap();
                    subMap.put("text", event.getText());
                    subMap.put("id", "event_" + event.getId());
                    subMap.put("cls", "folder");
                    subMap.put("expanded", true);
                    subMap.put("leaf", true);
                    subMap.put("checked", isCheckEvent(event.getId().intValue()));
                    children.add(subMap);
                }
                map.put("leaf", false);
                map.put("children", children);
            }
        }
    }
    /**
     * 
     * Description : 检查权限是否选中
     * 
     * @param code
     * @return boolean
     * 
     */
    private boolean isChecked(String code) {
        String roleId = request.getParameter("roleId");
        if (roleId == null) {
            return false;
        }

        Role role = roleService.queryById(Long.valueOf(roleId));
        Set<Right> rights = role.getRights();
        if (rights != null) {
            Iterator<Right> itor = rights.iterator();
            while (itor.hasNext()) {
                if (itor.next().getRightCode().equals(code)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    /**
     * 检测选中的事件
     * @param eventId
     * @return
     */
    private boolean isCheckEvent(int eventId) {
        String roleId = request.getParameter("roleId");
        if (roleId == null) {
            return false;
        }
        Role role = roleService.queryById(Long.valueOf(roleId));
        Set<ViewEvent>   viewSet= role.getEvents();
        if(viewSet!=null){
            for(ViewEvent event : viewSet){
                if(eventId==event.getId().intValue()){
                    return true;
                }
            }
        }
        return false;
    }
    
    

    /**
     * 
     * Description : 添加角色
     * 
     * @return String
     * @throws Exception
     * 
     */
    @SuppressWarnings("unchecked")
    public String add() throws Exception {
        String roleName = request.getParameter("roleName");
        String description = request.getParameter("description");
        String rightIds = request.getParameter("rightIds");

        if (StringUtils.isEmpty(rightIds)) {
            sendFailureMessage(Constants.MUST_SELECT_RIGHT);
            return null;
        }

        Role role = roleService.queryByName(roleName);
        if (role != null) {
            sendFailureMessage(Constants.EXIST_ROLE_NAME);
        } else {
            role = new Role();
            role.setRoleName(roleName);
            role.setDescription(description);

            Set<Right> rights = new HashSet();
            String[] arr = rightIds.split(",");
            Right right;
            Menu menu;
            Set<ViewEvent> events = new HashSet<ViewEvent>();
            for (int i = 0; i < arr.length; i++) {

                // rights分为menuID和事件ID,此处取出eventID,格式为event_10
                String eventId = "0";
                ViewEvent eventObj = new ViewEvent();
                if (arr[i].indexOf(AdamsConstant.ROLE_EVENT) > -1) {
                    eventId = arr[i].replace(AdamsConstant.ROLE_EVENT, "");
                    eventObj.setId(Long.parseLong(eventId));
                    events.add(eventObj);
                } else {
                    menu = menuService.queryById(Long.valueOf(arr[i]));
                    if (menu != null) {
                        right = rightService.queryByCode(menu.getMenuCode());
                        if (right != null) {
                            rights.add(right);
                        }
                    }
                }
            }
            role.setEvents(events);
            role.setRights(rights);
            roleService.createRole(role);

            // 记录日志
            createLog("addRole", "role name:" + roleName);

            // 发送提示信息
            sendSuccessMessage(Constants.ADD_SUCCESS);
        }
        return null;
    }

    /**
     * 
     * Description : 更新角色
     * 
     * @return String
     * @throws Exception
     * 
     */
    @SuppressWarnings("unchecked")
    public String update() throws Exception {
        String id = request.getParameter("id");
        String roleName = request.getParameter("roleName");
        String description = request.getParameter("description");
        String rightIds = request.getParameter("rightIds");

        Role role = roleService.queryByName(roleName);
        if (role != null && !role.getId().toString().equals(id)) {
            sendFailureMessage(Constants.EXIST_ROLE_NAME);
        } else {
            role = roleService.queryById(Long.valueOf(id));
            role.setRoleName(roleName);
            role.setDescription(description);

            Set<Right> rights = new HashSet();
            String[] arr = rightIds.split(",");
            Right right;
            Menu menu;
            Set<ViewEvent> events = new HashSet<ViewEvent>();
            for (int i = 0; i < arr.length; i++) {
                String eventId = "0";
                ViewEvent eventObj = new ViewEvent();
                if (arr[i].indexOf(AdamsConstant.ROLE_EVENT) > -1) {
                    eventId = arr[i].replace(AdamsConstant.ROLE_EVENT, "");
                    eventObj.setId(Long.parseLong(eventId));
                    events.add(eventObj);
                }else{
                    menu = menuService.queryById(Long.valueOf(arr[i]));
                    if (menu != null) {
                        right = rightService.queryByCode(menu.getMenuCode());
                        if (right != null) {
                            rights.add(right);
                        }
                    }
                }
                
            }
            role.setEvents(events);
            role.setRights(rights);
            roleService.updateRole(role);

            // 记录日志
            createLog("updateRole", "role name:" + roleName);

            sendSuccessMessage(Constants.UPDATE_SUCCESS);
        }
        return null;
    }

    /**
     * 
     * Description : 删除角色
     * 
     * @return String
     * @throws Exception
     * 
     */
    @SuppressWarnings("unchecked")
    public String delete() throws Exception {
        List<Map> mapList = ViewAction.getDataMap(request);
        Role role;
        for (Map map : mapList) {
            role = roleService.queryById(Long.valueOf((String) map.get("id")));
            roleService.deleteRole(role);
        }
        sendSuccessMessage(Constants.DELETE_SUCCESS);

        // 记录日志
        StringBuilder roleNames = new StringBuilder();
        for (Map map : mapList) {
            roleNames.append(map.get("roleName") + ",");
        }
        createLog("deleteRole", "role name:" + roleNames.substring(0, roleNames.length() - 1));
        return null;
    }

    /**
     * Description : 得到角色详细数据
     * 
     * @return String
     * @throws Exception
     * 
     */
    @SuppressWarnings("unchecked")
    public String get() throws Exception {

        List<Map> mapList = ViewAction.getDataMap(request);
        Map inputMap = null;
        if (mapList.size() > 0) {
            inputMap = ViewAction.getDataMap(request).get(0);
        }
        Map map = viewParseService.getDataByViewForm(getUserId(), menuId, formPanelId, inputMap);
        write(JSONObject.fromObject(map).toString());

        return null;
    }

    // /////////////////////属性设置/////////////////////////

    public void setMenuId(int menuId) {
        this.menuId = menuId;
    }

    public void setViewParseService(ViewParseService viewParseService) {
        this.viewParseService = viewParseService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    public void setRightService(RightService rightService) {
        this.rightService = rightService;
    }

    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

    public void setOptLogService(OptLogService optLogService) {
        this.optLogService = optLogService;
    }

    public void setViewEventId(String viewEventId) {
        this.viewEventId = viewEventId;
    }

    public void setViewItemId(String viewItemId) {
        this.viewItemId = viewItemId;
    }

    public void setFormPanelId(String formPanelId) {
        this.formPanelId = formPanelId;
    }

    public void setGridPanelId(String gridPanelId) {
        this.gridPanelId = gridPanelId;
    }

    public void setSearchPanelId(String searchPanelId) {
        this.searchPanelId = searchPanelId;
    }

    public ViewRoleEventService getViewRoleEventService() {
        return viewRoleEventService;
    }

    public void setViewRoleEventService(ViewRoleEventService viewRoleEventService) {
        this.viewRoleEventService = viewRoleEventService;
    }

}
